package ota;

import android.content.Context;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class Myhex {
	public static String buffer2String(final byte[] array) {
		if (array == null) {
			return "";
		}
		final StringBuffer sb = new StringBuffer();
		for (int length = array.length, i = 0; i < length; ++i) {
			sb.append(trim(Integer.toHexString(array[i])).toUpperCase() + " ");
		}
		return sb.toString();
	}

	public static String buffer2String(final byte[] array, final int n) {
		if (array == null) {
			return "";
		}
		final StringBuffer sb = new StringBuffer();
		new ArrayList();
		for (int i = 0; i < n; ++i) {
			sb.append(trim(Integer.toHexString(array[i])).toUpperCase() + " ");
		}
		return sb.toString();
	}

	public static byte[] hexStringToByte(final String s) {
		final String upperCase = s.replace(" ", "").toUpperCase();
		final int n = upperCase.length() / 2;
		final byte[] array = new byte[n];
		final char[] charArray = upperCase.toCharArray();
		for (int i = 0; i < n; ++i) {
			final int n2 = i * 2;
			array[i] = (byte) (toByte(charArray[n2]) << 4 | toByte(charArray[n2 + 1]));
		}
		return array;
	}

	public static void main(final String[] array) {
		showByte(hexStringToByte("A1b2"));
	}

	public static String parse02DString(final byte[] array) {
		if (array == null) {
			return "000000";
		}
		final StringBuffer sb = new StringBuffer();
		for (int length = array.length, i = 0; i < length; ++i) {
			sb.append("" + MyByte.byteToInt(array[i]));
		}
		return sb.toString();
	}

	public static String replaceBlank(final String s) {
		String replaceAll = "";
		if (s != null) {
			replaceAll = Pattern.compile("\\s*|\t|\r|\n").matcher(s).replaceAll("");
		}
		return replaceAll;
	}

	private static void showByte(final byte[] array) {
		final ArrayList<String> list = new ArrayList<String>();
		final ArrayList<String> list2 = new ArrayList<String>();
		for (final byte b : array) {
			list.add(trim(Integer.toHexString(b)).toUpperCase());
			list2.add(b + "");
		}
		System.out.println(list.toString());
		System.out.println(list2.toString());
	}

	public static int string2int(final String s) {
		final byte[] hexStringToByte = hexStringToByte(s);
		if (hexStringToByte == null) {
			return 0;
		}
		if (hexStringToByte.length == 0) {
			return 0;
		}
		if (hexStringToByte.length == 1) {
			return MyByte.byteToInt(hexStringToByte[0]);
		}
		return 256 * MyByte.byteToInt(-2 + hexStringToByte.length) + MyByte.byteToInt(-1 + hexStringToByte.length);
	}

	private static byte toByte(final char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	private static String trim(String s) {
		if (s.length() == 8) {
			s = s.substring(6);
		}
		if (s.length() == 1) {
			s = "0" + s;
		}
		return s;
	}

	public static boolean vali16Str(final String s) {
		final String replace = s.toUpperCase().replace(" ", "");
		for (int i = 0; i < replace.length(); ++i) {
			if ("0123456789ABCDEF".indexOf(replace.charAt(i)) < 0) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 读取文件内容
	 * 
	 * @param context
	 * @param filePath
	 * @return
	 */
	public static String getFileTxt(Context context, String filePath) {

		Map<Integer, String> map = new HashMap<Integer, String>();
		StringBuffer sb = new StringBuffer();
		try {
			File file = new File(filePath);
			int count = 0;// 初始化 key值
			if (file.isFile() && file.exists()) { // 文件存在的前提
				InputStreamReader isr = new InputStreamReader(new FileInputStream(file));
				BufferedReader br = new BufferedReader(isr);
				String lineTxt = null;
				while ((lineTxt = br.readLine()) != null) { //
					if (!"".equals(lineTxt)) {
						String reds = lineTxt.split("\\+")[0]; // java 正则表达式
						map.put(count, reds);// 依次放到map 0，value0;1,value2
						sb.append(reds);
						count++;
					}
				}
				isr.close();
				br.close();
			} else {
				Toast.makeText(context, "can not find file", Toast.LENGTH_SHORT).show();// 找不到文件情况下
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String resultContent = str2HexStr(sb.toString());
		System.out.println("读取到的原始内容:" + sb.toString());
		System.out.println("读取到的16进制内容:" + resultContent);
		try {
			getFileByte(context, filePath);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return resultContent;

	}

	public static void getFileByte(Context context, String filePath) throws IOException {

		// 1.按字节读写文件，用FileInputStream、FileOutputStream
		String path = filePath;
		File file = new File(path);
		InputStream in;
		// 每次只读一个字节
		try {
			System.out.println("以字节为单位，每次读取一个字节");
			in = new FileInputStream(file);
			int c;
			while ((c = in.read()) != -1) {
				if (c != 13 && c != 10) { // \n回车的Ascall码是10
											// ，\r换行是Ascall码是13，不现实挥着换行
					System.out.println((char) c);
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		// 每次读多个字节
		try {
			System.out.println("以字节为单位，每次读取多个字节");
			in = new FileInputStream(file);
			byte[] bytes = new byte[10]; // 每次读是个字节，放到数组里
			int c;
			while ((c = in.read(bytes)) != -1) {
				System.out.println("以字节为单位   " + Arrays.toString(bytes));
			}
		} catch (Exception e) {
		}

	}

	private static String str2HexStr(String str) {

		char[] chars = "0123456789ABCDEF".toCharArray();
		StringBuilder sb = new StringBuilder("");
		byte[] bs = str.getBytes();
		int bit;

		for (int i = 0; i < bs.length; i++) {
			bit = (bs[i] & 0x0f0) >> 4;
			sb.append(chars[bit]);
			bit = bs[i] & 0x0f;
			sb.append(chars[bit]);
			sb.append(' ');
		}
		return sb.toString().trim();
	}

	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toUpperCase();
		if (hexString.indexOf("0X") >= 0)
			hexString = hexString.replace("0X", "");
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	/**
	 * @Title: unicodeEncode
	 * @Description: unicode编码
	 * @param string
	 * @return
	 */
	public static String unicodeEncode(String string) {
		char[] utfBytes = string.toCharArray();
		String unicodeBytes = "";
		for (int i = 0; i < utfBytes.length; i++) {
			String hexB = Integer.toHexString(utfBytes[i]);
			if (hexB.length() <= 2) {
				hexB = "00" + hexB;
			}
			unicodeBytes = unicodeBytes + "\\u" + hexB;
		}
		return unicodeEncodeInvertedOrder(unicodeBytes);
	}

	/**
	 * 将原始数据倒叙处理
	 */
	public static String  unicodeEncodeInvertedOrder(String unicodeData){
		String dddddd=unicodeData.replace("\\u", "_");
		String []unicodeArray=dddddd.split("_");
		StringBuffer sb=new StringBuffer();
		for(int i=1;i<unicodeArray.length;i++){
			String headOld=unicodeArray[i].substring(0, 2);
			String endOld=unicodeArray[i].substring(2, 4);
			sb.append(endOld);
			sb.append(headOld);
		}
		return sb.toString();

	}


}
